<?php 

namespace Model;

Class CommentHandler
{
	const NOT_EMPTY = 0;
	const COMMENT_PASSED = 1;
	const COMMENT_FAILED = 2;
	const COMMENT_DELETED = 3;
	const COMMENT_NOT_DELETED = 4;
	private $database = null;

	public function __construct($m_database) {
		$this->database = $m_database;
	}
	//Alla funktioner här är gjorde för att ta imot värden som man sedan kastar in i databasen och gör olika saker med databasen.
	public function getCommentsFromPost($postId)
	{
		$stmt = $this->database -> Prepare('SELECT * FROM comments WHERE p_Id = (?) ORDER BY c_Id Desc');
		$stmt -> bind_param("i", $postId);
		$stmt -> execute();
		if ($stmt -> bind_result($commentId, $pId, $name, $comment,$date) == FALSE) {
			throw new Exception($this ->mysqli->error);
		}

		$stmt -> bind_result($commentId, $pId, $name, $comment,$date);

		$array = new CommentArray();

		while ($stmt -> fetch()) {
			$comments = new Comment($commentId, $pId, $name, $comment,$date);
			$array -> add($comments);
		}

		$stmt -> close();

		return $array;
	}
	

	public function NewComment ($pId,$name,$comment) {
		if (isset($name) && isset($comment)) {
			if ($name == "" || $comment == '') {
				return self::NOT_EMPTY;
			}
			//$vali = new \common\Validation();
			//if ($vali -> filterJavascript($name, $comment)) {
				if ($stmt = $this->database -> Prepare('INSERT INTO comments (p_Id,c_Name, c_Comment) VALUES (?,?,?)')) {
					$stmt -> bind_param('iss', $pId ,$name, $comment);
					$stmt -> execute();
					$stmt -> close();
					return self::COMMENT_PASSED;
				}
			//}
			return self::COMMENT_FAILED;
		}
	}

	public function DeleteComment($commentId) {
		if (isset($commentId)) {
			if ($stmt = $this->database->Prepare('DELETE FROM comments WHERE c_Id = (?)'))
			{
				$stmt -> bind_param('i', $commentId);
				$stmt -> execute();
				$stmt -> close();
				return self::COMMENT_DELETED;
			}
		}
		return self::COMMENT_NOT_DELETED;
	}
}